#pragma once
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <list>
#include <unordered_map>
#include <memory>
#include "thread_poll.hpp"
#include "timer_wheel.hpp"
#include <functional>
#include <signal.h>

int pipefd[2];
void signal_handler(int sig)
{
    //std::cout << "定时信号触发!" << std::endl;
    write(pipefd[1], (char *)&sig, 1);
}

typedef std::shared_ptr<char> buf_ptr;
#define EVENT_NUMBERS 1024
class chat_server
{
private:
    typedef std::shared_ptr<conndata> conn_ptr;

    void error_handler(const char *str)
    {
        printf("%s\n");
        exit(-1);
    }

    void setnoblocking(int fd)
    {
        int flags = fcntl(fd, F_GETFL, 0);
        fcntl(fd, F_SETFL, flags | O_NONBLOCK);
    }

    void read_msg(int sockfd)
    {
        char *read_buffer = _user_hash[sockfd]->buffer;
        int recv_len = 0;
        while (true)
        {
            recv_len = recv(sockfd, read_buffer, BUFFER_SIZE - 1, 0);
            if (recv_len > 0)
            {
                read_buffer[recv_len] = 0;
                printf("收到%d号客户端消息: %s\n", sockfd, read_buffer);

                // 更新定时器
                _tw.del_timer(_user_hash[sockfd]->_tr);
                timer *tr = _tw.add_timer(10);
                tr->_cb = std::bind(&chat_server::timer_callback,this,std::placeholders::_1);
                tr->_conn = _user_hash[sockfd].get();
                _user_hash[sockfd]->_tr = tr;
            }
            else if (recv_len == 0)
            {
                epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
                close(sockfd);
                _user_hash.erase(sockfd);
                printf("客户端退出!%d\n", sockfd);
                break; // 不需要再读取数据了
            }
            else
            {
                if (errno == EAGAIN)
                    break;
            }
        }
    }

    void send_msg(int sockfd)
    {
        int send_len = 0;
        char *send_buffer = _user_hash[sockfd]->buffer;
        for (auto &e : _user_hash)
        {
            if (e.second->_sockfd == sockfd)
                continue;
            printf("已向%d号客户端发送消息!\n", e.second->_sockfd);
            send(e.second->_sockfd, send_buffer, strlen(send_buffer), 0);
        }
    }

    void timer_handler()
    {
        _tw.tick();
        alarm(1);
    }

    void timer_callback(conndata *conn)
    {
        std::cout << conn->_sockfd << "号客户端长时间未动！服务器主动下线!" << std::endl;
        epoll_ctl(_epfd,EPOLL_CTL_DEL,conn->_sockfd,nullptr);
        close(conn->_sockfd);
        _user_hash.erase(conn->_sockfd);
    }
public:
    chat_server(int port)
        : _port(port), _pee(new epoll_event[EVENT_NUMBERS])
    {
        _listenfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listenfd == -1)
            error_handler("socket error!");

        int val = 1;
        int n = setsockopt(_listenfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
        if (n != 0)
            error_handler("setsockopt error!");

        sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = INADDR_ANY;
        n = bind(_listenfd, (sockaddr *)&server, sizeof(server));
        if (n == -1)
            error_handler("bind error!");

        n = listen(_listenfd, 16);
        if (n == -1)
            error_handler("listen error!");

        _epfd = epoll_create(64);
        setnoblocking(_listenfd);
        epoll_event event;
        event.data.fd = _listenfd;
        event.events = EPOLLIN;
        epoll_ctl(_epfd, EPOLL_CTL_ADD, _listenfd, &event);

        _tp.start(); // 线程池启动

        pipe(pipefd);
        setnoblocking(pipefd[1]);
        struct sigaction act;
        act.sa_flags = SA_RESTART; // 信号发生epoll_wait被唤醒，信号处理之后要继续阻塞
        act.sa_handler = signal_handler;
        sigaction(SIGALRM, &act, nullptr);
        event.data.fd = pipefd[0];
        event.events = EPOLLIN;
        epoll_ctl(_epfd, EPOLL_CTL_ADD, pipefd[0], &event);
    }

    void start()
    {
        alarm(1); // 一秒钟唤醒一次
        bool timeout = false;
        while (true)
        {
            int ret = epoll_wait(_epfd, _pee, EVENT_NUMBERS, -1);
            if (ret == -1)
            {
                if(errno == EINTR) continue;
                error_handler("epoll_wait error!");
            }
            if (ret == 0)
                continue;

            printf("有事件触发!数量: %d\n", ret);

            for (int i = 0; i < ret; i++)
            {
                if (_pee[i].data.fd == _listenfd)
                {
                    sockaddr_in client;
                    socklen_t len = sizeof(client);
                    int connfd = accept(_pee[i].data.fd, (sockaddr *)&client, &len);
                    setnoblocking(connfd);
                    epoll_event event;
                    event.data.fd = connfd;
                    event.events = EPOLLIN | EPOLLOUT | EPOLLET;
                    epoll_ctl(_epfd, EPOLL_CTL_ADD, connfd, &event);
                    printf("接收到新的客户端连接: %d\n", connfd);
                    //_sock_list.push_back(connfd);

                    timer *tr = _tw.add_timer(10);
                    conndata *conn = new conndata;
                    conn_ptr cp(conn);
                    tr->_cb = std::bind(&chat_server::timer_callback,this,std::placeholders::_1);
                    tr->_conn = conn;
                    cp->_tr = tr;
                    cp->_sockfd = connfd;

                    _user_hash.insert(std::make_pair(connfd, cp));
                }
                else if (_pee[i].data.fd == pipefd[0] && _pee[i].events & EPOLLIN)
                {
                    char signals[1024] = {0};
                    int n = read(pipefd[0], signals, sizeof(signals));
                    if (n == 0 || n == -1)
                        continue;
                    else
                    {
                        for (int i = 0; i < n; i++)
                        {
                            switch (signals[i])
                            {
                            case SIGALRM:
                                timeout = true;
                                break;
                            }
                        }
                    }
                }
                else if (_pee[i].events & EPOLLIN)
                {
                    // 向线程池添加任务
                    _tp.push(std::bind(&chat_server::read_msg, this, (int)_pee[i].data.fd));
                    printf("主线程获取到可读任务，并向线程池添加!\n");
                }
                if (_pee[i].events & EPOLLOUT)
                {
                    // 向线程池添加任务
                    _tp.push(std::bind(&chat_server::send_msg, this, (int)_pee[i].data.fd));
                    printf("主线程获取到可写任务，并向线程池添加!\n");
                }
                
                if(timeout)
                {
                    timer_handler();
                    timeout = false;
                }
            }
        }
    }

protected:
    int _listenfd;
    int _port;
    epoll_event *_pee;
    int _epfd;
    // std::list<int> _sock_list;// 存储用户连接的套接字
    std::unordered_map<int, conn_ptr> _user_hash; // 存储用户连接和缓冲区的映射
    thread_poll<std::function<void()>> _tp;
    timer_wheel _tw;
};